<template>
  <div class="swiper">
    <!-- 面包屑导航 -->
    <mybreadcrumb />

    <div class="opts">
      <el-button type="primary" @click="toswiperAdd">
        新增轮播图<el-icon><Plus /></el-icon>
      </el-button>
    </div>

    <!-- data 属性 控制表格中展示的数据 -->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" border stripe>
      <el-table-column label="序号" width="80" type="index" />
      <el-table-column label="图片" width="180" >
        <!-- 通过插槽实现表格列内容的自定义, scope 可以获取当前行 对象 -->
        <template #default="scope">
          <img :src="scope.row.img" alt="">
        </template>
      </el-table-column>
      <el-table-column label="图片链接" >
        <!-- 通过插槽实现表格列内容的自定义, scope 可以获取当前行 对象 -->
        <template #default="scope">
          <el-link :href="scope.row.link" type="primary">图片链接</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="alt" label="提示" />
      <el-table-column label="是否展示" >
        <template #default="scope">
          <el-switch v-model="scope.row.flag" @change="handleChange(scope.row.bannerid,scope.row.flag)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button @click="deleteBanner(scope.row.bannerid)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

  </div>
</template>

<script setup>

import {ref,onMounted} from 'vue'
import service from '@/api'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import 'element-plus/es/components/notification/style/css'

var $router = useRouter()

var loading = ref(false)

var tableData = ref([])

onMounted( async ()=>{
  //显示loading
  loading.value = true;
  //请求
  var res = await service.banner.banner_list();
  tableData.value = res.data.data;
  //隐藏loading
  loading.value = false;
})

var toswiperAdd = ()=>{
  $router.push('/index/swiperadd')
}
var handleChange = async (bannerid,flag)=>{
  //发请求, 更新图片的状态
  var res = await service.banner.banner_updateFlag( { bannerid,flag } );
  if( res.data.code == 200 ){
    ElNotification({
        title:'图片状态通知',
        message: '更新图片状态成功!',
        type:'success',
        duration: 1000
    })
  }
}
var deleteBanner = async (bannerid)=>{
  var res = await service.banner.banner_delete({ bannerid })
  if( res.data.code == 200 ){
    //查找下标
    var i = tableData.value.findIndex(item=>item.bannerid == bannerid)
    //删除图片
    if( i != -1 ) tableData.value.splice(i,1);

    // 或者
    // tableData.value = tableData.value.filter(item=>item.bannerid!=bannerid);
  }
}

</script>

<style scoped lang='scss'>
.swiper{
  .opts{
    margin: 20px 0;
  }
  img{
    object-fit: cover;
    width: 80%;
    height: 50px;
  }
}
</style>